package xiaopiya.robot.handler.translate;

import java.util.HashMap;
import java.util.Map;

import xiaopiya.robot.handler.AbstractMessageHandler;

/**
 * @author Ray (ayufox@gmail.com)
 * @version 0.1
 */
public class TranslateMessageHandler extends AbstractMessageHandler
{
	private Map<String, String> remenber = new HashMap<String, String>();

	private ITranslateService translateService;

	public void setTranslateService(ITranslateService translateService)
	{
		this.translateService = translateService;
	}

	protected String handle(String from, String source) throws Exception
	{
		source = source.trim();
		if (source.length() == 0)
		{
			return "";
		}
		String fromL = null;
		String toL = null;

		if (source.equals("-reset"))
		{
			this.remenber.remove(from);
			return "重置语言成功";
		}

		if (source.startsWith("-l"))
		{
			source = source.substring(2, source.length());
			int index = source.indexOf(' ');
			if (index < 0)
			{
				index = source.length();
			}
			String prefix = source.substring(0, index);
			String[] array = prefix.split("2");
			if (array.length != 2)
			{
				return "格式错误,请使用-l[from]2[to] [text],譬如-lzh2en 测试";
			}
			fromL = array[0];
			toL = array[1];

			if (this.translateService.isValidLanguage(fromL)
					&& this.translateService.isValidLanguage(toL))
			{
				this.remenber.put(from, prefix);
			}

			source = source.substring(index, source.length()).trim();
			
			if (source.length() == 0)
			{
				return "语言设置成功";
			}
		} else
		{
			String remember = this.remenber.get(from);
			if (remember != null)
			{
				String[] array = remember.split("2");

				fromL = array[0];
				toL = array[1];
			} else
			{
				String firstChar = source.substring(0, 1);
				// 中文
				if (firstChar.matches("[\\u4e00-\\u9fa5]+"))
				{
					fromL = "zh";
					toL = "en";
				} else
				{
					toL = "zh";
					fromL = "en";
				}
			}
		}
		
		return translateService.translate(fromL, toL, source);
	}
}